package com.gitee.blogcase.dealyqueuecase.java;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * juc 定义延迟对象信息
 * @author wuwentao
 */
@Data
public class OrderTimeoutDelayed implements Delayed {
    public OrderTimeoutDelayed(String orderId, long second){
        this.orderId = orderId;
        second = second * 1000;
        this.timeout = System.currentTimeMillis() + second;
    }
    private String orderId; // 订单号
    private long timeout; // 具体的超时时间

    /**
     *  延迟任务会自动调用该方法如果是负数则说明对象到了时间
     */
    @Override
    public long getDelay(TimeUnit unit) {
        return this.timeout - System.currentTimeMillis();
    }

    /**
     * 定义排序规则
     */
    @Override
    public int compareTo(Delayed o) {
        return (int) (getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS));
    }
}
